package com.sicheng.蓝桥.练习题;

import java.util.Arrays;
import java.util.Scanner;

/**
 * @author zsc
 * @version 1.0
 * @date 2022/5/18 10:54
 */
public class 记忆化搜索 {
    //https://mp.weixin.qq.com/s?__biz=Mzg4NDU4Njk2Nw==&mid=2247489904&idx=1&sn=86a03602d02a5d84da26abe1f0a9099a&chksm=cfb4b9c8f8c330de390071bbb7ab220c7f11b361bffa94d1ed582214da713d38b425ad601a53&scene=178&cur_album_id=1836587194044481541#rd
    private static final int[][] direction = {
            {1, 0},
            {-1, 0},
            {0, -1},
            {0, 1}
    };

    static int find(int[][] snowMountain, int[][] f, int i, int j, int r, int c) {
        int x, y;
        if (f[i][j] != -1)
            return f[i][j];
        f[i][j] = 1;
        for (int k = 0; k < 4; k++) {
            x = i + direction[k][0];
            y = j + direction[k][1];
            //valid direction
            if (x >= 0 && x < r && y >= 0 && y < c && snowMountain[i][j] > snowMountain[x][y]) {
                f[i][j] = Math.max(f[i][j], find(snowMountain, f, x, y, r, c) + 1);
            }
        }
        return f[i][j];
    }

    //输入
    //5 5
    //1 2 3 4 3
    //12 13 14 5 7
    //11 10 15 6 16
    //10 9 8 7 17
    //9 8 7 6 7

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int r = scanner.nextInt();
        int c = scanner.nextInt();
        int[][] map = new int[r][c];

        int[][] f = new int[r][c];
        for (int[] arr : f) {
            Arrays.fill(arr, -1);
        }
        for (int i = 0; i < r; i++) {
            for (int j = 0; j < c; j++) {
                map[i][j] = scanner.nextInt();
            }
        }

        int max = Integer.MIN_VALUE;
        for (int i = 0; i < r; i++) {
            for (int j = 0; j < c; j++) {
                max = Math.max(max, find(map, f, i, j, r, c));
            }
        }

        System.out.println(max);
    }
}
